<?php

require_once 'vendor/mustangostang/spyc/Spyc.php';
require_once 'vendor/autoload.php';

if ($_SERVER['HTTP_HOST'] == 'bimba.tk') {
    header('Location: https://apiote.tk/programs/bimba', true, 303);
    die();
}

$path = ltrim(@$_GET["path"], "/");

if (preg_match("/^[\/a-zA-Z_\-0-9]+.(svg|woff2|css|txt|webp|png|js)$/", $path) === 1) {
    $types = ['css' => 'text/css', 'js' => 'application/javascript', 'woff2' => 'font/woff2', 'png' => 'image/png', 'txt' => 'text/plain', 'svg' => 'image/svg+xml', 'webp' => 'image/webp'];
    $ext = pathinfo($path)['extension'];
    header("Content-Type: $types[$ext]");
    readfile($path);
    die;
}

if (preg_match("/^[\/a-zA-Z]+.sig$/", $path) === 1) {
    $yaml = Spyc::YAMLLoad(dirname($path) .'/'. basename($path, '.sig') . '.yml');
    $name = basename($path, '.sig');
    header('Content-Type: application/yaml');
    header("Content-Disposition: attachment; filename=\"$name.sig.yml\"");
    echo Spyc::YAMLDump($yaml['signature'], false, 0, true);
    die;
}

if (preg_match("/^[\/a-zA-Z]+.(php)$/", $path) === 1) {
    include $path;
    die;
}


if (preg_match("/^[\/a-zA-Z]*$/", $path) === 0) {
    http_response_code(404);
    die('404');
}

if ($path == '') {
    $path = './';
}

if (is_dir($path)) {
    doFile("${path}index");
} else {
    doFile($path);
}

function doFile($path) {
    $path = strtolower($path);
    if (file_exists("$path.yml")) {
        $yaml = Spyc::YAMLLoad("$path.yml");
        head($yaml['style'], $yaml['title'], $yaml['script']);
        switch($yaml['type']) {
            case 'file':
                $path = dirname($path);
                main("$path/$yaml[file]", array_key_exists('signature', $yaml));
                break;
            case 'listing':
                listing(dirname($path));
        }
        foot();
    } else {
        http_response_code(404);
        $quotes = Spyc::YAMLLoad("quotes.yml");
        $index = rand(0, count($quotes)-1);
        head(['main.css'], 'Not Found', []);
        echo '<h1><span class="error">error:</span> 404</h1>';
        echo $quotes[$index];
        foot();
        die;
    }
}

function listing($path) {
    $dir = scandir($path);
    $dir = array_filter($dir, function($v) {
                                  return preg_match('/^.*\.yml$/', $v) === 1 &&
                                         $v != 'index.yml';
                              });
    $yaml = Spyc::YAMLLoad("$path/index.yml");
    echo "<h1>$yaml[title]</h1>\n";
    echo "<p>$yaml[description]</p>\n";
    echo "<ul class=\"listing\">\n";
    foreach($dir as $file) {
        $yaml = Spyc::YAMLLoad("$path/$file");
        $a = "/$path/".basename($file, '.yml');
        echo "<li><a href=\"$a\"><span class=\"listing-title\">$yaml[title]</span></a><br/>";
        echo "<span class=\"listing-description\">$yaml[description]</span></li>";
    }
    echo "</ul>\n";
}

function head($styles, $title, $scripts) {
    echo <<<HEAD
<!DOCTYPE html>
<html>
    <head>
        <title>$title</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="icon" type="image/svg+xml" href="/img/logo.svg">
        <meta name="description" content="Apiote’s website">
        <meta name="og:description" content="Apiote’s website">
        <meta name="og:title" content="Apiote">
        <meta name="og:image" content="/img/preview.webp">
        <meta name="referrer" content="no-referrer">
        <meta name="theme-color" content="#911f1b">

        <link href="/feed/?format=atom" type="application/atom+xml" rel="alternate" title="Atom feed" />
        <link href="/feed/?format=json" type="application/json" rel="alternate" title="JSON feed" />
        
        <link rel="stylesheet" href="/style/plex.css">
        <link rel="stylesheet" href="/style/material.css">
        <link rel="stylesheet" href="/style/fontawesome.css">
        <link rel="stylesheet" href="/style/fira.css">

HEAD;
    foreach ($styles as $style) {
        echo "        <link rel=\"stylesheet\" href=\"/style/$style\">\n";
    }
    if ($scripts != []) {
        foreach ($scripts as $script) {
            echo "        <script src=\"/js/$script\"></script>\n";  # integrity
        }
    }
    echo <<<HEAD
    </head>
    <body>
        <header>
            <div id="logo">
                <a href="/"><img src="/img/logo.svg" alt="logo"></a>
            </div>
            <div>
                <a href="/"><div id="title">
                    Apiote
                </div></a>
                <nav>
                    <a href="/about">:about</a>
                    <a href="/programs/">:programs</a>
                    <a href="/manifestos/">:manifestos</a>
                    <a href="/donate">:donate</a>
                    <a href="/credits">:credits</a>
                    <a href="/contact">:contact</a>
                </nav>
            </div>
        </header>
        <main>
            <article>

HEAD;
}

function foot() {
    echo <<<FOOT
            </article>
            <hr id="aside-separator">
            <aside>
                <p>Computer science student. Fed up with business agenda.</p>
                <ul>
                    <li><i class="list-icon fas fa-code-branch"></i><a href="https://notabug.org/apiote">apiote</a></li>
                    <li><i class="list-icon fab fa-keybase"></i><a href="https://keybase.io/apiote">apiote</a></li>
                    <li><i class="list-icon material-icons">fingerprint</i><a href="https://keyserver.ubuntu.com/pks/lookup?op=vindex&search=0x2442e27776e0a578&fingerprint=on">0x2442e27776e0a578</a></li>
                    <li><i class="list-icon fab fa-mastodon"></i><a href="https://floss.social/@apiote">@apiote@floss.social</a></li>
                    <li class="wrap"><i class="list-icon fab fa-monero"></i><code>46siw2guCQWQiNAdTBCAvVY1uGYhsFQBuEStBgh4shrfBETMNsMDi9MHoMWyjrVYxEPNKFHsodZ31EcC9FM2R2nMCF21bAJ</code></li>
                    <li class="wrap"><img src="/img/zcash_logo.svg" alt="zcash" class="list-icon"><code>zcTTKeUpznTKe3nuZ182t3GnWEyhRGwnCWm613k7PYgMCGvKebekV3px844x8S2KGhA7JVFYHb7cn1Xm2ZpK2QnWzcmrnMm</code></li>
                </ul>
                <p>The license for this website is <a href="https://www.gnu.org/licenses/agpl-3.0.en.html">AGPL</a></p>
                <p class="anouncement">The domain ‘adamsptogs.tk’ will not be prolonged and will cease to exist in April 2019. To still be able to visit this website head to <a href="https://apiote.tk">apiote.tk</a></p>
            </aside>
        </main>
    </body>
</html>
FOOT;
}


function main($filename, $signature) {
    if ($signature) {
        $basename = basename($filename, '.rst');
        $basename = basename($basename, '.html');
        $sig = dirname($filename, 2). '/' . $basename . '.sig';
         echo "<a href=\"$sig\"><i class=\"sig small-icon material-icons\">lock</i> this document is signed</a>";
    }
    switch(pathinfo($filename)['extension']) {
        case 'html':
            readfile($filename);
            break;
        case 'rst':
            $parser = new Gregwar\RST\Parser;
            $rst = file_get_contents($filename);
            $document = $parser->parse($rst);
            echo $document;
            break;
    }
}

?>
